<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad"
    >
      <template #menu-left>

        <el-button type="warning"
                   size="small"
                   plain
                   icon="el-icon-download"
                   v-if="permission.commodityrecord_export"
                   @click="handleExport">导出
        </el-button>

        <el-button type="primary"
                   size="small"
                   plain
                   icon="el-icon-circle-check"
                   v-if="permission.commodityrecord_edit"
                   @click="handleConfirm">一键确认
        </el-button>
      </template>
      <template #menu="{row}">
        <el-button text
                   type="primary"
                   icon="el-icon-circle-check"
                   v-if="permission.commodityrecord_edit && row.status === 1"
                   plain
                   style="border: 0;background-color: transparent !important;"
                   @click.stop="rowConfirm(row)">确认
        </el-button>
      </template>

      <template #status="{row}">
        <el-tag v-if="row.status === 1"  type="primary">{{row.$status}}</el-tag>
        <el-tag v-else-if="row.status === 2" type="success">{{row.$status}}</el-tag>
        <el-tag v-else-if="row.status === 3"  type="warning">{{row.$status}}</el-tag>
        <el-tag v-else-if="row.status === 4"  type="danger">{{row.$status}}</el-tag>
        <el-tag v-else>{{row.$status}}</el-tag>
      </template>

      <template #info-form="{}">
        <avue-crud :option="infoOption"
                   :data="form.info"
                   :permission="permissionList"
                   @row-update="infoRowUpdate"
                   @row-del="infoRowDel"
        ></avue-crud>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, exportCheck,confirm} from "@/api/restaurant/commodityrecord";
import {update as infoRowUpdate, remove as infoRowDel} from "@/api/restaurant/commodityrecordrelation";

import {mapGetters} from "vuex";
import {baseUrl} from "@/config/env";
import { getToken } from '@/utils/auth';
import { serialize } from '@/utils/util';

export default {
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      page: {
        pageSize: 100,
        currentPage: 1,
        total: 0,
        searchTime:[]
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 210,
        searchShow: true,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        editBtn:false,
        selection: true,
        column: [
          {
            label: "下单人",
            prop: "userId",
            multiple: false,
            filterable: true,
            search: true,
            type: "tree",
            dicUrl: baseUrl + "/restaurant/common/user-list",
            props: {
              label: "name",
              value: "id"
            },
            rules: [{
              required: true,
              message: "请输入下单人",
              trigger: "click"
            }]
          },
          {
            label: "状态",
            type: "select",
            dicUrl: baseUrl + "/blade-system/dict/dictionary?code=commodity_status",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            prop: "status",
            search: true,
            rules: [{
              required: true,
              message: "请输入状态",
              trigger: "blur"
            }]
          },
          {
            label: "摘要",
            prop: "summary"
          },
          {
            label: "备注",
            prop: "remark"
          },
          {
            label: "下单时间",
            prop: "createTime",
          },
          {
            label: "下单时间",
            hide: true,
            prop: "searchTime",
            type: 'datetime',
            format: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            search: true,
            searchSpan: 8,
            searchRange: true,
            disabledDate (time) {
              return time.getTime() > Date.now();
            },
          },
          {labelWidth: 0, label: '', prop: 'info', span: 24, hide: true}

        ]
      },
      infoOption: {
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,
        cellBtn: true,  // 是否显示行内按钮
        selection: false,
        showSummary: true, // 统计
        sumColumnList: [
          { name: 'number', type: 'sum', decimals: 1 },
          { name: 'actualNumber', type: 'sum', decimals: 1 },
        ],
        column: [
          {
            label: "货物名",
            prop: "commodityName",
            rules: [{
              required: true,
              message: "请输入货物名",
              trigger: "blur"
            }]
          },
          {
            label: "类别名",
            prop: "categoryName",
            rules: [{
              required: true,
              message: "请输入类别名",
              trigger: "blur"
            }]
          },
          {
            label: "货物图",
            prop: "productPicture",
            type: "upload",
            listType: "picture-img",
            action: "/api/blade-resource/oss/endpoint/put-file",
            propsHttp: {
              res: 'data',
              url: 'link'
            },
            rules: [{
              required: true,
              message: "请输入货物图",
              trigger: "blur"
            }]
          },
          {
            label: "数量",
            prop: "number",
            type: "number",
            precision: 0,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: "请输入数量",
              trigger: "blur"
            }]
          },
          {
            label: "实到数量",
            prop: "actualNumber",
            type: "number",
            precision: 2,
            min: 0,
            cell: true,
            rules: [{
              required: true,
              message: "请输入实到数量",
              trigger: "blur"
            }]
          },
          {
            label: "单位",
            prop: "unit",
            rules: [{
              required: true,
              message: "请输入单位",
              trigger: "blur"
            }]
          },
          {
            label: "备注",
            prop: "remark",
            rules: [{
              required: true,
              message: "请输入备注",
              trigger: "blur"
            }]
          },
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: false,
        viewBtn: this.validData(this.permission.commodityrecord_view, false),
        delBtn: this.validData(this.permission.commodityrecord_delete, false),
        editBtn: this.validData(this.permission.commodityrecord_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    infoRowUpdate(row, index, done, loading) {
      infoRowUpdate(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    infoRowDel(row, index, done, loading) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
            return infoRowDel(row.id);
          }
      ).then(() => {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      });
    },
    rowSave(row, done, loading) {
      add(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        done();
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        window.console.log(error);
        loading();
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    async handleExport() {
      let  status = false;
      // 是否存在未确认的数据 不存在: false  存在: true
      await exportCheck(this.query.searchTime).then(res => {
        console.info(JSON.stringify(res))
        if (res.data.data) {
          this.$message.warning(`您有未确认的数据，请先确认${this.query.searchTime?this.query.searchTime[0]+' 至 '+this.query.searchTime[1]:'今日'}采购数据，在进行导出操作！`);
          status  = true;
        }
      })

      if (status) {
        return;
      }
      console.info(".........." +  status)
      this.$confirm(`确定导出${this.query.searchTime?this.query.searchTime[0]+' 至 '+this.query.searchTime[1]:'今日'}已确认的采购明细?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        window.open(`/api/restaurant/commodityrecord/export?blade-auth=bearer ${getToken()}&` + serialize(this.query));
      });
    },
    rowConfirm(row){
      this.$confirm("确定将选择数据设置为已确认?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
          return confirm(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleConfirm(){
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
    this.$confirm("确定将选择数据设置为已确认?", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(() => {
        return confirm(this.ids);
      })
      .then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        this.$refs.crud.toggleSelection();
      });
    }
  }
};
</script>

<style>
</style>
